<template>
  <Combination
    ref="comSharePercentageRef"
    class="price-udp"
    :items="comItem"
    :comData="ruleForm.data"
    :rules="comRules"
    :size="maxSize"
    :isAllDelete="true"
    @data-minus="dataMinus"
  ></Combination>
</template>

<script lang="ts" setup name="share-percentage">
import { FormRules, FormInstance } from 'element-plus';
import Combination from '@/components/combination/combination.vue';
import { IS_0_100_1 } from '@/utils/verify';

const comSharePercentageRef = ref();

let optionsS = reactive({
  org: [] as any,
});
let maxSize = ref(1);

const ruleForm = reactive({
  data: [] as any,
});

const comItem = reactive([
  {
    comName: 'select',
    labelWidth: 0,
    prop: 'operatorId',
    width: 219,
    isOnly: true,
    props: {
      prepend: '参与分润方',
      options: optionsS.org,
    },
  },
  {
    comName: 'input',
    labelWidth: 0,
    prop: 'sharePercentage',
    width: 300,
    props: {
      prepend: '分润比例',
      append: '%',
      maxlength: 10,
      placeholder: '请输入分润比例',
      input: (index: number, form: any) => {
        console.log('333---', index, form);
        let num = 0;
        form.data.forEach((item: any) => {
          if (item.sharePercentage) {
            num += Number(item.sharePercentage);
          }
        });
        emit('total-percentage', num);
      },
    },
  },
]);

const checkPercentage = (rule: any, value: any, callback: any) => {
  const data = comSharePercentageRef.value?.getData();
  let num = 0;
  data.forEach((item: any, inx: number) => {
    num += Number(item.sharePercentage);
  });
  if (num > 100) {
    callback(new Error('分润比例总和不能大于100'));
  }
  callback();
};
const comRules = reactive<FormRules>({
  operatorId: [
    {
      required: true,
      message: '请选择参与分润方',
      trigger: ['blur', 'change'],
    },
  ],
  sharePercentage: [
    { required: true, message: '请输入分润比例', trigger: 'blur' },
    {
      pattern: IS_0_100_1,
      message: '请输入正确的分润比例，精确到1位小数',
      trigger: 'blur',
    },
    // { validator: checkPercentage, trigger: 'blur' },
  ],
});

const getOrgData = (arr: any) => {
  console.log('arr---', arr);
  optionsS.org = [...arr];
  comItem[0].props.options = [...arr];
  nextTick(() => {
    comSharePercentageRef.value?.setOptions(0, 0, optionsS.org);
    comSharePercentageRef.value?.setItemDatas(optionsS.org);
  });
  maxSize.value = arr.length;
};

const emit = defineEmits(['set-percentage', 'total-percentage']);
const dataMinus = (index: number, item: any) => {
  const data = comSharePercentageRef.value?.getData();
  if (data.length === 1) {
    emit('set-percentage', false);
  }
};

const getData = async () => {
  if (!comSharePercentageRef.value) return;
  try {
    await Promise.all([comSharePercentageRef.value.validate()]);
  } catch (fields: any) {
    for (const key in fields) {
      if (fields[key]) {
        comSharePercentageRef.value.scrollToField(key);
        break;
      }
    }
    return false;
  }

  const data = comSharePercentageRef.value?.getData();
  let num = 0;
  data.forEach((item: any) => {
    num += Number(item.sharePercentage);
  });
  if (num > 100) {
    ElMessage({
      showClose: true,
      message: '分润比例和不能大于100%',
      type: 'warning',
    });
    comSharePercentageRef.value.scrollToField('data.[0][sharePercentage]');
    return false;
  }
  return data;
};

const setData = (data: any, id: string, arr: any) => {
  ruleForm.data = [];
  let num = 0;
  data.forEach((item: any, index: number) => {
    if (item.operatorId !== id) {
      if (index === 0) {
        getOrgData(arr);
      } else {
        nextTick(() => {
          comSharePercentageRef.value?.setOptions(index, 0, arr);
        });
      }
      ruleForm.data.push({
        operatorId: Number(item.operatorId),
        sharePercentage: String(item.sharePercentage),
      });
      num += Number(item.sharePercentage);
    }
  });
  emit('total-percentage', num);
};
defineExpose({
  getOrgData,
  getData,
  setData,
});
</script>

<style lang="scss" scoped>
:deep(.item-wrap) {
  margin-bottom: 18px;
}
</style>